package com.gxuwz.jwt.util;

import com.gxuwz.jwt.entity.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.context.annotation.Bean;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class JwtUtil {

    //创建jwt
    public static String createJWT(long expirationDate , User user){
        //签名算法
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

        //生成Jwt时间
        long jwtTime = System.currentTimeMillis();
        Date date = new Date(jwtTime);

        //创建payload私有声明
        Map<String,Object> map = new HashMap<>();
        map.put("userId",user.getUserId());
        map.put("userName",user.getUserName());
        map.put("password",user.getPassword());
        map.put("role",user.getRole());
        //生成签名的时候使用的密钥secret
        String key = user.getPassword();

        //签发人
        String subject = user.getUserName();
        //为payload添加各种标准
        JwtBuilder jwtBuilder = Jwts.builder().setClaims(map)
                                              .setId(UUID.randomUUID().toString().replace("_",""))
                                              .setIssuedAt(date)
                                              .setSubject(subject)
                                              .signWith(signatureAlgorithm,key);
        if (expirationDate >= 0){
            long expDate = jwtTime + expirationDate;
            Date exp = new Date(expDate);
            System.out.println("exp "+exp);
            jwtBuilder.setExpiration(exp);
        }
        return jwtBuilder.compact();
    }

    //Token解密
    public static Claims decryptJWT(String token , User user){
        //签名密钥
        String key = user.getPassword();

        Claims claims = Jwts.parser().setSigningKey(key)
                                      //需要解析的jwt
                                     .parseClaimsJws(token).getBody();
        return claims;
    }

    //验证token
    public static  Boolean checkJWT(String token , User user){
        //签名密钥
        String key = user.getPassword();
        System.out.println("key "+key);
        try {
            Claims claims = Jwts.parser().setSigningKey(key)
                    .parseClaimsJws(token).getBody();
            System.out.println("claims key "+claims.get("password"));
            if (claims.get("password").equals(user.getPassword())){
                return true;
            }
        }catch (RuntimeException e){
            e.printStackTrace();
        }
        return false;
    }

}
